Date.prototype.format = function (format) //author: meizz
{
    var o = {
        "M+": this.getMonth() + 1, //month
        "d+": this.getDate(),    //day
        "h+": this.getHours(),   //hour
        "m+": this.getMinutes(), //minute
        "s+": this.getSeconds(), //second
        "q+": Math.floor((this.getMonth() + 3) / 3),  //quarter
        "S": this.getMilliseconds() //millisecond
    }
    if (/(y+)/.test(format)) format = format.replace(RegExp.$1,
    (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o) if (new RegExp("(" + k + ")").test(format))
        format = format.replace(RegExp.$1,
      RegExp.$1.length == 1 ? o[k] :
        ("00" + o[k]).substr(("" + o[k]).length));
    return format;
}
function formatTime(val) {
    try {
        if (val.indexOf('-') >= 0) {
            return val;
        }
        else {
            var d = new Date();
            var re = /-?\d+/;
            var m = re.exec(val);
            var d = new Date(parseInt(m[0]));
            return d.format("yyyy-MM-dd");
        }
    } catch (e) {
        return "";
    }
}
function getQueryString(name) {
    var svalue = location.href.match(new RegExp("[\?\&]" + name + "=([^\&]*)(\&?)", "i"));
    return svalue ? svalue[1] : svalue;
}
function getSeldatetypeStr(type) {
    var str = '';
    if ('0' == type) {
        str = '今日';
    } else if ('1' == type) {
        str = '本周';
    } else if ('2' == type) {
        str = '本月';
    } else if ('3' == type) {
        str = '上月';
    } else {
        str = '本月';
    }
    return str;
}
function get_calltagstr(val) {
    if (val == '0') {
        return '未拨打';
    }
    else {
        return '已拨打';
    }
}

function get_followtagstr(val) {
    if (val == '3') {
        return '已成交';
    }
    else if (val == '2') {
        return '待跟进';
    }
    else if (val == '1') {
        return '无意向';
    }
    else {
        return '未标记';
    }
}
angular.module('tasklist.controller', [])
  .controller('tasklistCtrl', ['$scope', '$timeout', '$localstorage', '$ionicPopup', 'tasklistService', '$state', 'loginService', '$ionicModal', function ($scope, $timeout, $localstorage, $ionicPopup, tasklistService, $state, loginService, $ionicModal) {
      $scope.tasklist = [];
      $scope.custinfo = {};
      //$scope.seldatetype = '2';
      $scope.seldatestr = '本月';
      $scope.follwcustinfo = {};
      //$scope.statesel = 'count';
      $scope.statelist = [{ title: '总数', name: 'count', value: 0 },
      { title: '未打', name: 'callstate0', value: 0 },
      { title: '已打', name: 'callstate1', value: 0 },
      { title: '无意', name: 'followState1', value: 0 },
      { title: '待跟', name: 'followState2', value: 0 },
      { title: '成交', name: 'followState3', value: 0 }];
      $scope.params = tasklistService.getParams();


      $ionicModal.fromTemplateUrl('popview/custfollowmodal.html', {
          scope: $scope 
      }).then(function (modal) {
          $scope.modal = modal;
      });

      $scope.$on('$ionicView.enter', function (event, data) {
          console.log("任务页面进来了");
          $scope.seldatetype = getQueryString('seldatetype');
          var search = getQueryString('search');
          if (search != null && search != '') $('#input_search').val(decodeURI(search));
          if ($scope.seldatetype == null || $scope.seldatetype == '') $scope.seldatetype = '2';
          $scope.seldatestr = getSeldatetypeStr($scope.seldatetype);
          $scope.params.Depart_Code = $localstorage.get("Depart_Code");
          $scope.params.User_ID = $localstorage.get("User_ID");
          $scope.params.Phone = $localstorage.get("Phone");
          if ($scope.tasklist.length <= 0) {
              $scope.doRefresh();
          }
      });


      $ionicModal.fromTemplateUrl('popview/taskdatesel.html', {
          scope: $scope
      }).then(function (modal) {
          $scope.taskdateselmodal = modal;
      });

      $scope.doRefresh = function () { 
          $scope.params.fields = 'Task_ID,Task_Name,IN_Date,Manage_Name';
          $scope.params.order = 'IN_Date desc';
          $scope.params['searchstr'] = $('#input_search').val();
          $scope.params['seldatetype'] = $scope.seldatetype;
          $scope.params.Task_ID = '-1';

          tasklistService.get_tasklist($scope.params).then(function (data) {
              if (data.length > 0) {
                  for (var i = 0; i < data.length; i++) {
                      data[i].IN_Date = formatTime(data[i].IN_Date);
                  }
                  $scope.params.Task_ID = data[0].Task_ID;
                  $scope.fun_statesel("count");
              }
              $scope.tasklist = data;
              $scope.custinfo = {};
          }, function (error) {
              var alertPopup = $ionicPopup.alert({
                  title: '获取在网导航失败！',
                  template: "异常错误",
                  okText: '确定', // String (默认: 'OK')。OK按钮的文字。
                  okType: 'item-customer-bg-darkred', // String (默认: 'button-positive')。OK按钮的类型。
              });
          });
      };

      $scope.refreshCustlist = function () {
          $scope.params.showcount = 0;
          $('#loadMore').show(); 
          $scope.params.page = 1;//刷新显示第一页 
          $scope.params.order = 'Call_State asc'; 
          tasklistService.get_taskcustlist($scope.params).then(function (data) {
              if (data.list.length > 0) {
                  for (var i = 0; i < data.list.length; i++) {
                      data.list[i].laststartdate = formatTime(data.list[i].laststartdate);
                      data.list[i].Call_State_Str = get_calltagstr(data.list[i].Call_State.trim());
                      data.list[i].Follow_State_Str = get_followtagstr(data.list[i].Follow_State.trim());
                      $scope.params.showcount++;
                  }
              }
              $scope.custinfo = data;

              if ($scope.params.showcount >= $scope.custinfo[$scope.params.selstate]) {
                  $('#loadMore').hide();
              }
              $('.tasklist').css({ overflow: 'hidden', backgroundColor: "#f7f7f7", width: '100%' });
              $('#m_' + $scope.params.Task_ID.trim()).css({ overflow: 'visible', backgroundColor: "#fff", width: '101%' });
               
          }, function (error) {
              var alertPopup = $ionicPopup.alert({
                  title: '获取在网导航失败！',
                  template: "异常错误",
                  okText: '确定',  
                  okType: 'item-customer-bg-darkred', 
              });
          });
      }

      $scope.loadMoreCustlist = function () {
          $scope.params.page ++; 
          $scope.params.order = 'Call_State asc';
          tasklistService.get_taskcustlist($scope.params).then(function (data) {
              if (data.list.length > 0) {
                  for (var i = 0; i < data.list.length; i++) {
                      data.list[i].laststartdate = formatTime(data.list[i].laststartdate);
                      data.list[i].Call_State_Str = get_calltagstr(data.list[i].Call_State.trim());
                      data.list[i].Follow_State_Str = get_followtagstr(data.list[i].Follow_State.trim());
                      $scope.custinfo.list.push(data.list[i]);
                      $scope.params.showcount++;
                  }
              }
              if ($scope.params.showcount >= $scope.custinfo[$scope.params.selstate]) {
                  $('#loadMore').hide();
              }

          }, function (error) {
              var alertPopup = $ionicPopup.alert({
                  title: '获取失败！',
                  template: "无法获取更多内容",
                  okText: '确定',
                  okType: 'item-customer-bg-darkred',
              });
          });
      }

      $scope.callSomething = function (custphone) { 
          $scope.params.Cust_Phone = custphone.trim();
          console.log("------------------------------$scope.params.Cust_Phone：" + custphone);
          var _params = {};
                    _params['Depart_Code'] = $scope.params.Depart_Code;
                    _params['User_ID'] = $scope.params.User_ID;
                    _params['Phone'] = $scope.params.Phone;
                    _params['Task_ID'] = $scope.params.Task_ID;
                    _params['Call_Phone'] = custphone;
                    _params['Cust_Phone'] = custphone;
                    _params['Call_Staff'] = $scope.params.User_ID;
          var nowdate=new Date();
          var extraInfo = cordova.require('com.onluy.plugins.telemanager.telemanager');
          extraInfo.DoSome('Tel', _params,
          function (message) {   },
          function (message) { alert(message); });
          window.open('tel:' + custphone);
          for (var i = 0; i < $scope.custinfo.list.length; i++) {
                            var obj = $scope.custinfo.list[i];
                            if (custphone.trim() == obj.Cust_Phone.trim() && $scope.params.Task_ID.trim() == obj.Task_ID.trim()) {
                                $scope.custinfo.list[i].Call_State = '1';
                                $scope.custinfo.list[i].Call_State_Str = get_calltagstr('1');
                                $scope.custinfo.list[i].laststartdate = nowdate.format("yyyy-MM-dd hh:mm:ss");
                                $scope.custinfo.list[i].cellcount =(
                                    $scope.custinfo.list[i].cellcount == null || $scope.custinfo.list[i].cellcount==''?
                                    1 : $scope.custinfo.list[i].cellcount+1
                                    );
                                break;
                            }
                        }
      }

      $scope.follostateshow = function (info) {
          $scope.follwcustinfo = info;
          $scope.modal.show();
      }

      $scope.fun_statesel = function ( field) { 
          $(".t_statesel").removeClass("border_bottom");
          $(".t_statesel").addClass("border_bottom");
          $('#t_' + field).removeClass("border_bottom");
          $scope.params.selstate = field;
          $scope.refreshCustlist();
      }

      $scope.fun_tasksel = function (taskid) {
          $scope.params.Task_ID = taskid.trim(); 
          $scope.fun_statesel("count");
      }

      $scope.fun_datesel = function (type) {
          $scope.seldatetype = type;
          $scope.seldatestr = getSeldatetypeStr(type); 
          $scope.taskdateselmodal.hide();
          $scope.doRefresh();
      }


      $scope.upfollostate = function (state) { 
          $scope.params.Task_ID = $scope.follwcustinfo.Task_ID.trim();
          $scope.params.Cust_Phone = $scope.follwcustinfo.Cust_Phone.trim();
          $scope.params.Follow_State = state;
          tasklistService.get_uptaskcustcallstate($scope.params).then(function (data) {
              if (data.success == false) return;
              for (var i = 0; i < $scope.custinfo.list.length; i++) {
                  var obj = $scope.custinfo.list[i];
                  if ($scope.follwcustinfo.Cust_Phone == obj.Cust_Phone && $scope.follwcustinfo.Task_ID == obj.Task_ID) {
                      $scope.custinfo.list[i].Follow_State = state;
                      $scope.custinfo.list[i].Follow_State_Str = get_followtagstr(state);
                      break;
                  }
              }
              $scope.modal.hide()
          }, function (error) {
              var alertPopup = $ionicPopup.alert({
                  title: '异常！',
                  template: "请联网后再标记！" + error,
                  okText: '确定',
                  okType: 'item-customer-bg-darkred',
              });
          });
      } 

  }]);
